﻿using JNPF.Basics.Models;
using JNPF.Data;
using JNPF.Data.Util;
using JNPF.Utils;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Linq.Expressions;
using System.Text;
using System.Threading.Tasks;

namespace JNPF.Basics.Logic
{
    /// <summary>
    /// 定时任务
    /// 版 本：V3.0.0
    /// 版 权：引迈信息技术有限公司（https://www.jnpfsoft.com）
    /// 作 者：JNPF开发平台组
    /// 日 期：2017-12-12
    /// </summary>
    public class TimeTaskService : DataFactory, TimeTaskIService
    {
        /// <summary>
        /// 列表
        /// </summary>
        /// <param name="input">请求参数</param>
        /// <returns></returns>
        public async Task<PageResult<TimeTaskEntity>> GetList(PageInput input)
        {
            using (var db = this.Basic)
            {
                var queryWhere = ExtLinq.True<TimeTaskEntity>();
                var queryParam = input.queryJson.ToObject();
                //关键字（编码、名称）
                if (!string.IsNullOrEmpty(input.keyword))
                {
                    queryWhere = queryWhere.And(m => m.FullName.Contains(input.keyword) || m.EnCode.Contains(input.keyword));
                }

                return await db.GetIQueryable<TimeTaskEntity>().Where(queryWhere).OrderByDescending(t => t.CreatorTime).GetPageResultAsync(input);
            }
        }

        public async Task<List<TimeTaskEntity>> GetList()
        {
            using (var db = this.Basic)
            {
                return await db.GetListAsync<TimeTaskEntity>();
            }
        }
        /// <summary>
        /// 列表（执行记录）
        /// </summary>
        /// <param name="input">请求参数</param>
        /// <param name="taskId">任务Id</param>
        /// <returns></returns>
        public async Task<PageResult<TimeTaskLogEntity>> GetTaskLogList(PageInput input, string taskId)
        {
            using (var db = this.Basic)
            {
                var queryWhere = ExtLinq.True<TimeTaskLogEntity>();
                var queryParam = input.queryJson.ToObject();
                //关键字
                if (!string.IsNullOrEmpty(input.keyword))
                {
                    queryWhere = queryWhere.And(m => m.TaskId == taskId);
                }

                return await db.GetIQueryable<TimeTaskLogEntity>().Where(queryWhere).OrderByDescending(t => t.RunTime).GetPageResultAsync(input);
            }
        }
        /// <summary>
        /// 信息
        /// </summary>
        /// <param name="id">主键值</param>
        /// <returns></returns>
        public async Task<TimeTaskEntity> GetInfo(string id)
        {
            using (var db = this.Basic)
            {
                return await db.GetEntityAsync<TimeTaskEntity>(m => m.Id == id);
            }
        }
        /// <summary>
        /// 验证
        /// </summary>
        /// <param name="whereLambda">条件</param>
        /// <returns></returns>
        public async Task<bool> IsExist(Expression<Func<TimeTaskEntity, bool>> whereLambda)
        {
            using (var db = this.Basic)
            {
                return (await db.GetCountAsync(whereLambda) > 0);
            }
        }
        /// <summary>
        /// 删除
        /// </summary>
        /// <param name="entity">实体对象</param>
        /// <returns></returns>
        public async Task<int> Delete(TimeTaskEntity entity)
        {
            using (var db = this.Basic)
            {
                CronUtil.Instance.Remove(entity);
                return await db.DeleteAsync(entity);
            }
        }
        /// <summary>
        /// 创建
        /// </summary>
        /// <param name="entity">实体对象</param>
        /// <returns></returns>
        public async Task<int> Create(TimeTaskEntity entity)
        {
            using (var db = this.Basic)
            {
                var userInfo = UserProvider.Instance.Get();
                var tenantId = userInfo.TenantId;
                var time = DateTime.Now;
                var contentModel = JsonHelper.ToObject<ContentModel>(entity.ExecuteContent);
                contentModel.name = entity.FullName;
                if (contentModel.frequency == "1" || contentModel.frequency == "2")
                {
                    var cycle = CronUtil.Instance.GetOneCron(contentModel, entity.ExecuteCycleJson);
                    if (cycle != "")
                    {
                        entity.ExecuteCycleJson = cycle;
                    }
                    else
                    {
                        entity.ExecuteCycleJson = time.Second + " " + time.Minute + " " + time.Hour + " " + time.Day + " " + time.Month + " " + "?";
                    }

                }
                else if (contentModel.frequency == "3")
                {
                    var listCron = CronUtil.Instance.GetMoreCron(contentModel);
                    StringBuilder builder = new StringBuilder();
                    foreach (var item in listCron)
                    {
                        builder.Append(item + ";");
                    }
                    entity.ExecuteCycleJson = builder.ToString();
                }
                else if (contentModel.frequency == "4")
                {
                    entity.ExecuteCycleJson = contentModel.cron;
                }
                entity.RunCount = 0;
                tenantId = tenantId != "" ? tenantId : userInfo.UserAccount;
                //开启定时任务
                CronUtil.Instance.StartJobAsync(entity, contentModel, tenantId);
                return await db.InsertAsync(entity);
            }
        }

        /// <summary>
        /// 更新
        /// </summary>
        /// <param name="entity">实体对象</param>
        /// <returns></returns>
        public async Task<int> Update(TimeTaskEntity entity)
        {
            using (var db = this.Basic)
            {
                var userInfo = UserProvider.Instance.Get();
                var tenantId = userInfo.TenantId;
                var dbName = userInfo.TenantDbConnectionString;
                var contentModel = JsonHelper.ToObject<ContentModel>(entity.ExecuteContent.ToString());
                tenantId = !string.IsNullOrEmpty(tenantId) ? tenantId : userInfo.UserAccount;
                //定时任务赋值
                if (entity.EnabledMark == 0)
                {
                    if (contentModel.frequency != "3")
                    {
                        CronUtil.Instance.Remove(entity);
                    }
                    else
                    {
                        string[] cycle = entity.ExecuteCycleJson.Split(";");
                        for (int i = 0; i < cycle.Length; i++)
                        {
                            CronUtil.Instance.Remove(entity);
                        }
                    }
                }
                contentModel.name = entity.FullName;
                CronUtil.Instance.StartJobAsync(entity, contentModel, tenantId);
                return await db.UpdateAsync(entity);
            }
        }

        /// <summary>
        /// 执行记录
        /// </summary>
        /// <param name="entity">实体对象</param>
        /// <returns></returns>
        public async Task<int> CreateTaskLog(TimeTaskLogEntity entity)
        {
            using (var db = this.Basic)
            {
                return await db.InsertAsync(entity);
            }
        }
    }
}